package com.suxin.netty.ws;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

/**
 * @Classname MyTextWebSocketFrameHandler
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2021/1/6 22:34
 * @Created by ASUS
 */
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("sever receive msg：" + msg.text());
        ctx.channel().writeAndFlush(new TextWebSocketFrame(LocalDateTime.now() + "服务器回复：" + msg.text()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // ctx.channel().id().asLongText()  唯一的 id
        System.out.println("[客户端" + ctx.channel().remoteAddress() + "] 上线了..." + ctx.channel().id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("[客户端" + ctx.channel().remoteAddress() + "] 离线了..." + ctx.channel().id().asLongText());
    }
}